package module.StoreService.Impl;

import dao.StoreDao.OrderItemDao;
import common.model.Entity.StoreEntity.OrderItem;
import dao.impl.StoreDaoImpl.OrderItemDaoImpl;
import module.StoreService.OrderItemService;
import network.protocol.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Optional;

/**
 * {@code OrderItemServiceImpl} 是 {@link OrderItemService} 的实现类，
 * 提供订单项（OrderItem）的增删改查、批量操作以及金额统计等功能。
 * <p>
 * 主要功能：
 * <ul>
 *     <li>根据 ID 或订单 ID 获取订单项</li>
 *     <li>获取所有订单项</li>
 *     <li>创建、批量创建、更新、删除订单项（逻辑删除）</li>
 *     <li>根据订单 ID 删除订单项</li>
 *     <li>统计订单项数量，计算订单总金额</li>
 * </ul>
 * <p>
 * 实现逻辑通过 {@link OrderItemDao} 与数据库交互，
 * 并使用 {@link Response} 封装统一的操作结果。
 * <p>
 * 类采用单例模式，请通过 {@link #getInstance()} 获取实例。
 */
public class OrderItemServiceImpl implements OrderItemService {
    private static final Logger logger = LoggerFactory.getLogger(OrderItemServiceImpl.class);
    private final OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private static final OrderItemServiceImpl INSTANCE = new OrderItemServiceImpl();

    /**
     * 私有构造函数，防止外部直接实例化。
     */
    private OrderItemServiceImpl() {}

    /**
     * 获取 {@code OrderItemServiceImpl} 的单例对象。
     *
     * @return 单例实例
     */
    public static OrderItemServiceImpl getInstance() {
        return INSTANCE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<Optional<OrderItem>> getOrderItemById(long id) {
        try {
            Optional<OrderItem> orderItem = orderItemDao.findById(id);
            return Response.success(orderItem);
        } catch (Exception e) {
            logger.error("获取订单项失败: id={}", id, e);
            return Response.error("获取订单项失败: " + e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<List<OrderItem>> getOrderItemsByOrderId(long orderId) {
        try {
            List<OrderItem> orderItems = orderItemDao.findByOrder(orderId);
            return Response.success(orderItems);
        } catch (Exception e) {
            logger.error("获取订单项失败: orderId={}", orderId, e);
            return Response.error("获取订单项失败: " + e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<List<OrderItem>> getAllOrderItems() {
        try {
            List<OrderItem> orderItems = orderItemDao.findAll();
            return Response.success(orderItems);
        } catch (Exception e) {
            logger.error("获取所有订单项失败", e);
            return Response.error("获取所有订单项失败: " + e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<Boolean> createOrderItem(OrderItem orderItem) {
        try {
            // 验证订单项数据
            if (orderItem.getOrderId() <= 0) {
                logger.warn("创建订单项失败: 订单ID无效");
                return Response.error("订单ID无效");
            }
            if (orderItem.getProductId() <= 0) {
                logger.warn("创建订单项失败: 商品ID无效");
                return Response.error("商品ID无效");
            }
            if (orderItem.getQuantity() <= 0) {
                logger.warn("创建订单项失败: 数量必须大于0");
                return Response.error("数量必须大于0");
            }
            if (orderItem.getPrice() < 0) {
                logger.warn("创建订单项失败: 价格不能为负数");
                return Response.error("价格不能为负数");
            }

            boolean result = orderItemDao.save(orderItem);
            return result ? Response.success(true) : Response.error("创建订单项失败");
        } catch (Exception e) {
            logger.error("创建订单项失败: orderId={}, productId={}",
                    orderItem.getOrderId(), orderItem.getProductId(), e);
            return Response.error("创建订单项失败: " + e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<Boolean> updateOrderItem(OrderItem orderItem) {
        try {
            // 确保订单项存在
            if (orderItemDao.findById(orderItem.getId()).isEmpty()) {
                logger.warn("更新订单项失败: 未找到ID为 {} 的订单项", orderItem.getId());
                return Response.error("未找到订单项");
            }
            // 验证订单项数据
            if (orderItem.getQuantity() <= 0) {
                logger.warn("更新订单项失败: 数量必须大于0");
                return Response.error("数量必须大于0");
            }
            if (orderItem.getPrice() < 0) {
                logger.warn("更新订单项失败: 价格不能为负数");
                return Response.error("价格不能为负数");
            }

            boolean result = orderItemDao.update(orderItem);
            return result ? Response.success(true) : Response.error("更新订单项失败");
        } catch (Exception e) {
            logger.error("更新订单项失败: id={}", orderItem.getId(), e);
            return Response.error("更新订单项失败: " + e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<Boolean> deleteOrderItem(long id) {
        try {
            if (orderItemDao.findById(id).isEmpty()) {
                logger.warn("删除订单项失败: 未找到ID为 {} 的订单项", id);
                return Response.error("未找到订单项");
            }

            boolean result = orderItemDao.deleteById(id);
            return result ? Response.success(true) : Response.error("删除订单项失败");
        } catch (Exception e) {
            logger.error("删除订单项失败: id={}", id, e);
            return Response.error("删除订单项失败: " + e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<Boolean> deleteOrderItemsByOrderId(long orderId) {
        try {
            boolean result = orderItemDao.deleteByOrder(orderId);
            return result ? Response.success(true) : Response.error("删除订单项失败");
        } catch (Exception e) {
            logger.error("删除订单项失败: orderId={}", orderId, e);
            return Response.error("删除订单项失败: " + e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<Long> getOrderItemCount() {
        try {
            long count = orderItemDao.count();
            return Response.success(count);
        } catch (Exception e) {
            logger.error("获取订单项总数失败", e);
            return Response.error("获取订单项总数失败: " + e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<Double> calculateOrderTotal(long orderId) {
        try {
            List<OrderItem> orderItems = orderItemDao.findByOrder(orderId);
            double total = orderItems.stream()
                    .mapToDouble(item -> item.getPrice() * item.getQuantity())
                    .sum();
            return Response.success(total);
        } catch (Exception e) {
            logger.error("计算订单总金额失败: orderId={}", orderId, e);
            return Response.error("计算订单总金额失败: " + e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Response<Boolean> createOrderItems(List<OrderItem> orderItems) {
        try {
            if (orderItems == null || orderItems.isEmpty()) {
                logger.warn("批量创建订单项失败: 订单项列表为空");
                return Response.error("订单项列表为空");
            }

            boolean allSuccess = true;
            for (OrderItem item : orderItems) {
                Response<Boolean> result = createOrderItem(item);
                if (!result.isSuccess() || !Boolean.TRUE.equals(result.getData())) {
                    allSuccess = false;
                    logger.error("批量创建订单项失败: 无法创建订单项 orderId={}, productId={}",
                            item.getOrderId(), item.getProductId());
                }
            }

            return allSuccess ? Response.success(true) : Response.error("批量创建订单项失败");
        } catch (Exception e) {
            logger.error("批量创建订单项失败", e);
            return Response.error("批量创建订单项失败: " + e.getMessage());
        }
    }
}
